/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.globussoft.amazons3;
import com.cloudminga.database.DataBaseHelper;
import org.jets3t.service.security.AWSCredentials;
import org.jets3t.service.S3Service;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import java.io.File;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.multithread.DownloadPackage;
import org.jets3t.service.multithread.S3ServiceSimpleMulti;

/**
 *
 * @author Krunal Barot
 */
public class AmazonS3Utility {

    S3Service s3Service = null;
    DataBaseHelper databaseHelper;
    private static int fileTransfer;
    private static long sizeTransfer;

    public S3Service getS3Service() {
        try {
            s3Service = new RestS3Service(LoginAWS("AKIAJAJMP2WHMGUZ4V6A", "D1rljwv96zvgTutj9lfkoqRkXYci+qihNyZPqcFb"));
        } catch (Exception ex) {
        }
        return s3Service;
    }

    public static int getFileTransfer() {
        return fileTransfer;
    }

    public static long getSizeTransfer() {
        return sizeTransfer;
    }

    public static void setFileTransfer(int size) {
        fileTransfer = size;
    }

    public static void setSizeTransfer(long size) {
        sizeTransfer = size;
    }

    public AmazonS3Utility() {
        databaseHelper = new DataBaseHelper();
    }

    public boolean checkAvaibelityUserName(String username) {
        boolean status = false;
        S3Service s3service = getS3Service();
        try {
            S3Bucket tempBucket = s3service.getBucket(username);
            if (tempBucket == null) {
                tempBucket = s3service.getOrCreateBucket(username);
                status = true;
                s3Service.deleteBucket(tempBucket);
            }

        } catch (Exception ex) {
            status = false;
        }
        return status;
    }

    // Function To Create bucket
    public S3Bucket CreateBucket(String bucketname)//AWSCredentials awsCredentials, String userName, S3Service s3Service) {
    {
        S3Bucket userBucket = new S3Bucket();

        try {
            //User user login name for the bucket name. If it contains '@'
            //then it will be replaced by '-' as '@' is not allowed.
            //  AWSCredentials awsCredentials = LoginAWS(awsAccessKey, awsSecretKey);

            try {
                s3Service = getS3Service(); //new RestS3Service(awsCredentials);

            } catch (Exception e) {
                e.printStackTrace();
            }
            bucketname = bucketname.replace('@', '-');
            //This  will create bucket. It will not give error if the bucket is already created.
            //The access key is used to avoid conflict with the name space used in AWS which gives exception.
            userBucket = s3Service.getOrCreateBucket(bucketname);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return userBucket;
    }

    public AWSCredentials LoginAWS(String awsAccessKey, String awsSecretKey) {
        AWSCredentials awsCredentials =
                new AWSCredentials(awsAccessKey, awsSecretKey);
        return awsCredentials;
    }

    public Boolean UploadFile(String filePath, S3Bucket userBucket) {
        try {
            File fileData = new File(filePath);
            //Creating the s3 object
            if (fileData.isFile()) {
                System.out.println("Uploading ..." + filePath + "  " + Thread.currentThread().getName());
                S3Object fileObject = new S3Object(fileData);
                //Uploading the object on server
                s3Service.putObject(userBucket, fileObject);
            }
        } catch (Exception e) {
            System.out.println("The following error occured while uploading :");
            e.printStackTrace();
        }
        return true;
    }

    public void UploadFile(String filepath, String Bucketname) {
        try {
            File fileData = new File(filepath);
            if (fileData.isFile()) {
                System.out.println("Uploading ..." + filepath + "Bucket name =" + Bucketname + " " + Thread.currentThread().getName());
                S3Object s3obj = new S3Object(fileData);
                S3Bucket bucket = getS3Service().getBucket(Bucketname);
                S3Object putObject = s3Service.putObject(bucket, s3obj);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void DownloadFile(String BucketName, String FileName, String pathToStore, boolean renameIfFileExist, long startTime, String user, String restore) {
        try {
            if (pathToStore.trim().equals("")) {
                pathToStore = FileName.replace("\\", "/").substring(0, FileName.replace("\\", "/").lastIndexOf("/"));
            }
            try {
                s3Service = getS3Service();// new RestS3Service(awsCredentials);
            } catch (Exception e) {
                e.printStackTrace();
            }
            S3Bucket s3se = s3Service.getOrCreateBucket(BucketName);
            S3Object[] obj = s3Service.listObjects(s3se);
            DownloadPackage[] downloadpackage = new DownloadPackage[1];
            String filename = "";
            for (int i = 0; i < obj.length; i++) {
                // System.out.println(obj[i].getKey().toLowerCase() + "  " + FileName.toLowerCase().substring(FileName.toLowerCase().lastIndexOf("/") + 1));
                if (obj[i].getKey().toLowerCase().trim().equals(FileName.trim().toLowerCase().substring(FileName.toLowerCase().lastIndexOf("/") + 1))) {
                    filename = pathToStore.replace("\\", "/") + "/" + obj[i].getKey();
                    if (renameIfFileExist) {
                        if (new File(pathToStore.replace("\\", "/") + "/" + obj[i].getKey()).exists()) {
                            filename = getFileName(pathToStore.replace("\\", "/") + "/" + obj[i].getKey());
                        }
                    }
                    downloadpackage[0] = new DownloadPackage(obj[i], new File(filename));
                    break;
                }
            }
            S3ServiceSimpleMulti s3servicemulti = new S3ServiceSimpleMulti(s3Service);
            long start = new java.util.Date().getTime();
            s3servicemulti.downloadObjects(s3se, downloadpackage);
            long end = new java.util.Date().getTime();
            databaseHelper.insertIntoBackupDetailTb(user, startTime, FileName, (end - start), "");
            fileTransfer++;
            sizeTransfer += new File(filename).length();
            if (restore.equals("Restore")) {
                databaseHelper.insertIntoRestoreTb(user, startTime, FileName, pathToStore);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void DownloadFile(String BucketName, String FileName) {
        try {
            try {
                s3Service = getS3Service();// new RestS3Service(awsCredentials);
            } catch (Exception e) {
                e.printStackTrace();
            }
            S3Bucket s3se = s3Service.getOrCreateBucket(BucketName);
            S3Object[] obj = s3Service.listObjects(s3se);
            DownloadPackage[] downloadpackage = new DownloadPackage[1];
            for (int i = 0; i < obj.length; i++) {
                if (obj[i].getKey().equals(FileName)) {
                    downloadpackage[0] = new DownloadPackage(obj[i], new File(obj[i].getKey()));
                    break;
                }
            }
            S3ServiceSimpleMulti s3servicemulti = new S3ServiceSimpleMulti(s3Service);
            s3servicemulti.downloadObjects(s3se, downloadpackage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void DownloadFile(String BucketName) {
        try {
            try {
                s3Service = getS3Service();//  new RestS3Service(awsCredentials);
            } catch (Exception e) {
                e.printStackTrace();
            }
            S3Bucket s3se = s3Service.getBucket(BucketName);
            S3Object[] obj = s3Service.listObjects(s3se);
            DownloadPackage[] downloadpackage = new DownloadPackage[obj.length];
            for (int i = 0; i < obj.length; i++) {
                downloadpackage[i] = new DownloadPackage(obj[i], new File(obj[i].getKey()));
            }
            S3ServiceSimpleMulti s3servicemulti = new S3ServiceSimpleMulti(s3Service);
            s3servicemulti.downloadObjects(s3se, downloadpackage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void DownloadAll() {
        try {
            try {
                s3Service = getS3Service();//new RestS3Service(awsCredentials);
            } catch (Exception e) {
                e.printStackTrace();
            }
            S3Bucket[] s3bucket = s3Service.listAllBuckets();
            for (int j = 0; j < s3bucket.length; j++) {
                //  if(s3bucket[j].getName().contains("sunil")){
                //    System.out.println(s3bucket[j].getName());
                S3Object[] s3obj = s3Service.listObjects(s3bucket[j]);
                DownloadPackage[] down = new DownloadPackage[s3obj.length];
                for (int i = 0; i < s3obj.length; i++) {
                    down[i] = new DownloadPackage(s3obj[i], new File(s3obj[i].getKey()));
                }
                S3ServiceSimpleMulti s3servicemulti = new S3ServiceSimpleMulti(s3Service);
                s3servicemulti.downloadObjects(s3bucket[j], down);
                //           }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void UploadFileTree() {
    }

    public static void main(String[] arg) {
        AmazonS3Utility amagen = new AmazonS3Utility();
        // System.out.println(amagen.checkAvaibelityUserName("sunil"));
        //  S3Bucket bucket = amagen.CreateBucket("sunilkumar");
        // amagen.UploadFile("C:/Index.txt",bucket); //, bucket,amagen.getS3Service());
        amagen.DeleteAllBucket();
        // amagen.DownloadAll();
        //amagen.DownloadFile("AKIAJAJMP2WHMGUZ4V6A.sunilkumar");//, "Sunil.txt");
    }

    public void DeleteAllBucket() {
        try {
            s3Service = getS3Service();// new RestS3Service(awsCredentials);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            S3Bucket[] s3se = s3Service.listAllBuckets();
            for (int i = 0; i < s3se.length; i++) {
                try {
                    if (s3se[i].getName().contains("globussoft")) {
                        System.out.println("Deleting ...." + s3se[i].getName());
                        S3Object[] bucket = s3Service.listObjects(s3se[i]);
                        for (int j = 0; j < bucket.length; j++) {
                            s3Service.deleteObject(s3se[i], bucket[j].getKey());
                        }
                        s3Service.deleteBucket(s3se[i]);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
//                    Map map = s3se[i].getMetadataMap();
//                    Object[] obj = map.keySet().toArray();
//                    for (int j = 0; j < obj.length; j++) {
//                        System.out.println(obj[i]);
//                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String getFileName(String filename) {
        int counter = 0;
        while (new File(filename).exists()) {
            filename = (filename.contains("(" + counter + ").")) ? (filename.replace("(" + counter + ").", "(" + (++counter) + ")."))
                    : filename.substring(0, filename.indexOf(".")) + "(" + (++counter) + ")"
                    + filename.substring(filename.indexOf("."));
        }
        return filename;
    }
//(filename.contains("("+counter+")."))?(filename.replace("("+counter+").","("+(++counter)+").")):
}
